package com.cmge.ad.controller.crawl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmge.ad.cache.ehcache.EhCacheCacheManager;
import com.cmge.ad.controller.BaseController;
import com.cmge.ad.model.Crawl;
import com.cmge.ad.model.CrawlLog;
import com.cmge.ad.model.JsonResult;
import com.cmge.ad.model.Result;
import com.cmge.ad.service.CrawlService;
import com.cmge.ad.spider.PorcessorManager;
import com.cmge.ad.util.Constant;
import com.cmge.ad.util.Pager;
import com.cmge.ad.util.SuprUtil;

/**
 * @desc	爬虫管理
 * @author	ljt
 * @time	2015-1-27 下午4:40:18
 */
@Controller
public class CrawlController extends BaseController{
	
	public static final Logger logger = Logger.getLogger(CrawlController.class);
	
	@Autowired
	private CrawlService crawlService;
	
	@Autowired
	private EhCacheCacheManager cacheManager;
	
	/**
	 * 跳转新增爬虫页面
	 */
	@RequestMapping("/addArticleCrawl")
	public String addArticleCrawl(){
		return "/adCrawl/crawl/add_article_crawl";
	}
	
	/**
	 * 跳转新增爬虫页面 （new）
	 */
	@RequestMapping("/addArticleCrawlNew")
	public String addArticleCrawlNew(){
		return "/adCrawl/crawl/add_article_crawl_new";
	}
	
	/**
	 * 跳转新增爬虫页面
	 */
	@RequestMapping("/addAlbumCrawl")
	public String addAlbumCrawl(){
		return "/adCrawl/crawl/add_album_crawl";
	}
	
	/**
	 * 跳转爬虫列表页面
	 */
	@RequestMapping("/crawlList")
	public String crawlList(){
		return "/adCrawl/crawl/crawl_list";
	}
	
	/**
	 * 段子仓库列表
	 */
	@RequestMapping("/getCrawlList")
	public @ResponseBody
	JsonResult getCrawlList(HttpSession session,Pager<Crawl> pager,Crawl crawl) {
		JsonResult result = new JsonResult();
		HashMap<String, Object> paramMap = new HashMap<String,Object>();
		
		paramMap.put("crawl", crawl);
		crawlService.getCrawlList(pager,paramMap);
		result.setData(pager.getRows());
		result.setTotalCount(pager.getTotalCount());
		return result;
	}
	
	
	/**
	 * 新增爬虫任务
	 */
	@RequestMapping("/addCrawlInfo")
	public @ResponseBody
	Result addCrawlInfo(Crawl crawl) throws UnsupportedEncodingException{
		
		if(!StringUtils.isEmpty(crawl.getInfoContentXpath())){
			crawl.setInfoContentXpath(URLDecoder.decode(crawl.getInfoContentXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getListUrlRegular())){
			crawl.setListUrlRegular(URLDecoder.decode(crawl.getListUrlRegular(), "utf-8"));
		}

		if(!StringUtils.isEmpty(crawl.getInfoUrlRegular())){
			crawl.setInfoUrlRegular(URLDecoder.decode(crawl.getInfoUrlRegular(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoContentXpath())){
			crawl.setInfoContentXpath(URLDecoder.decode(crawl.getInfoContentXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoPicXpath())){
			crawl.setInfoPicXpath(URLDecoder.decode(crawl.getInfoPicXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getRepeatFlagXpath())){
			crawl.setRepeatFlagXpath(URLDecoder.decode(crawl.getRepeatFlagXpath(), "utf-8"));
		}
		
//		if(!StringUtils.isEmpty(crawl.getListUrlRegular())){
//			crawl.setListUrlRegular(URLDecoder.decode(crawl.getListUrlRegular(), "utf-8"));
//		}
		
//		if(!StringUtils.isEmpty(crawl.getInfoUrlXpath())){
//			crawl.setInfoUrlXpath(URLDecoder.decode(crawl.getInfoUrlXpath(), "utf-8"));
//		}
		
		crawlService.addCrawl(crawl);
		return new Result("success", Constant.DEAL_SUCCESS);
	}
	
	/**
	 * 新增爬虫任务
	 */
	@RequestMapping("/addAlbumCrawlInfo")
	public @ResponseBody
	Result addAlbumCrawlInfo(Crawl crawl) throws UnsupportedEncodingException{
		
		if(!StringUtils.isEmpty(crawl.getInfoContentXpath())){
			crawl.setInfoContentXpath(URLDecoder.decode(crawl.getInfoContentXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getListUrlRegular())){
			crawl.setListUrlRegular(URLDecoder.decode(crawl.getListUrlRegular(), "utf-8"));
		}

		if(!StringUtils.isEmpty(crawl.getInfoUrlRegular())){
			crawl.setInfoUrlRegular(URLDecoder.decode(crawl.getInfoUrlRegular(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoContentXpath())){
			crawl.setInfoContentXpath(URLDecoder.decode(crawl.getInfoContentXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoPicXpath())){
			crawl.setInfoPicXpath(URLDecoder.decode(crawl.getInfoPicXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getRepeatFlagXpath())){
			crawl.setRepeatFlagXpath(URLDecoder.decode(crawl.getRepeatFlagXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoUrlXpath())){
			crawl.setInfoUrlXpath(URLDecoder.decode(crawl.getInfoUrlXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoListNextXpath())){
			crawl.setInfoListNextXpath(URLDecoder.decode(crawl.getInfoListNextXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoListNextXpath())){
			crawl.setInfoListNextXpath(URLDecoder.decode(crawl.getInfoListNextXpath(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getInfoFirstRegular())){
			crawl.setInfoFirstRegular(URLDecoder.decode(crawl.getInfoFirstRegular(), "utf-8"));
		}
		
		if(!StringUtils.isEmpty(crawl.getTitleXpath())){
			crawl.setTitleXpath(URLDecoder.decode(crawl.getTitleXpath(), "utf-8"));
		}
		
		crawlService.addAlbumCrawlInfo(crawl);
		return new Result("success", Constant.DEAL_SUCCESS);
	}
	
	
	/**
	 * 获取爬虫日志
	 */
	@RequestMapping("/getCrawlLogById")
	public String getCrawlLogById(ModelMap map,String id) {
		Object obj = cacheManager.get("CrawlLog", id);
		List<CrawlLog> logList = new ArrayList<CrawlLog>();
		ConcurrentLinkedQueue<CrawlLog> queue = null;
		if(obj != null){
			queue = (ConcurrentLinkedQueue<CrawlLog>)obj;
			CrawlLog crawlLog = null;
			while((crawlLog = queue.poll()) != null){
				logList.add(crawlLog);
			}
		}
		
		Crawl crawl = crawlService.scanCrawlTaskById(id);
		
		map.addAttribute("crawl", crawl);
		map.addAttribute("logList", logList);
		map.addAttribute("id", id);
		return "/adCrawl/crawl/crawl_log_info";
	}
	
	/**
	 * 编辑爬虫设置
	 */
	@RequestMapping("/editCrawlById")
	public String editCrawlById(ModelMap map,String id) {
		Crawl crawl = crawlService.scanCrawlTaskById(id);
		
		map.addAttribute("crawl", crawl);
		return "/adCrawl/crawl/update_crawl_info";
	}
	
	@RequestMapping("/getIncrCrawlLogById")
	public @ResponseBody
	JsonResult getIncrCrawlLogById(String id){
		JsonResult result = new JsonResult();
		StringBuilder sb = new StringBuilder();
		Object obj = cacheManager.get("CrawlLog", id);
		
		List<CrawlLog> logList = new ArrayList<CrawlLog>();
		ConcurrentLinkedQueue<CrawlLog> queue = null;
		if(obj != null){
			queue = (ConcurrentLinkedQueue<CrawlLog>)obj;
			CrawlLog crawlLog = null;
			while((crawlLog = queue.poll()) != null){
				logList.add(crawlLog);
			}
		}
		
		if(!SuprUtil.isEmptyCollection(logList)){
			for (CrawlLog crawlLog : logList) {
				buildStr(sb, crawlLog);
			}
		}
		
		result.setData(sb.toString());
		return result;
	}

	private void buildStr(StringBuilder sb, CrawlLog crawlLog) {
		sb.append("<span class='log-time'>"+crawlLog.getTime()+"</span>");
		sb.append("<div class='log-con'>");
		sb.append(crawlLog.getLog());
		sb.append("</div>");
	}
	
	/**
	 * 重启爬虫任务
	 */
	@RequestMapping("/restartCrawlTaskById")
	public @ResponseBody
	Result restartCrawlTaskById(String id){
		Crawl crawl = crawlService.scanCrawlTaskById(id);
		if(crawl.getType() == 1){
			if(PorcessorManager.stopArticleProcessorById(id)){
				crawlService.starCralTaskById(id);
				return new Result("success", Constant.DEAL_SUCCESS);
			}else{
				return new Result("fail", Constant.DEAL_FAIL);
			}
		}else if(crawl.getType() == 2){
			if(PorcessorManager.stopAlbumProcessorById(id)){
				crawlService.starCralTaskById(id);
				return new Result("success", Constant.DEAL_SUCCESS);
			}else{
				return new Result("fail", Constant.DEAL_FAIL);
			}
		}
		
		return new Result("fail", Constant.DEAL_FAIL);
	}
	
	/**
	 * 更新爬虫设置
	 */
	@RequestMapping("/updateCrawlInfo")
	public @ResponseBody
	Result updateCrawlInfo(Crawl crawl){
		crawlService.updateCrawlInfo(crawl);
		return new Result("success", Constant.DEAL_SUCCESS);
	}
	
	/**
	 * 停止爬虫任务
	 */
	@RequestMapping("/stopCrawlTaskById")
	public @ResponseBody
	Result stopCrawlTaskById(String id){
		Crawl crawl = crawlService.scanCrawlTaskById(id);
		if(crawl.getType() == 1){
			if(PorcessorManager.stopArticleProcessorById(id)){
				return new Result("success", Constant.DEAL_SUCCESS);
			}else{
				return new Result("fail", Constant.DEAL_FAIL);
			}
		}else if(crawl.getType() == 2){
			if(PorcessorManager.stopAlbumProcessorById(id)){
				return new Result("success", Constant.DEAL_SUCCESS);
			}else{
				return new Result("fail", Constant.DEAL_FAIL);
			}
		}
		
		return new Result("fail", Constant.DEAL_FAIL);
	}
	
}
